package com.starxg.m3u8.gui;

import java.io.File;

import com.starxg.m3u8.config.ApplicationConfig;
import com.starxg.m3u8.controller.InitializationControl;
import com.starxg.m3u8.controller.InitializationWindow;
import com.starxg.m3u8.controller.MainController;

import javafx.scene.control.*;
import javafx.stage.FileChooser;
import lombok.Getter;

@Getter
public class TopMenuBar extends MenuBar implements InitializationControl<MainController>, InitializationWindow {
    private MainController controller;
    private MenuItem openFile;
    private MenuItem merger;
    private MenuItem poJie;
    private MenuItem about;

    @Override
    public void init(MainController controller) {
        this.controller = controller;
        initView();
        initData();
        initEvent();
    }

    @Override
    public void initView() {
        Menu file = new Menu("文件");
        file.getItems().add(openFile = new MenuItem("打开"));
        file.getItems().add(merger = new MenuItem("合并"));
        merger.setVisible(false);

        Menu other = new Menu("其他");
        other.getItems().add(poJie = new MenuItem("52破解"));
        other.getItems().add(about = new MenuItem("关于"));

        getMenus().addAll(file, other);
    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {
        openFile.setOnAction(e -> {
            File file = DialogUtils.showOpenFileDialog(null, null, controller.getStage(),
                    new FileChooser.ExtensionFilter("m3u8 file", "*.m3u8"));
            if (file != null) {
                controller.getControlController().getTxtUrl().setText(file.toURI().toString());
            }
        });

        poJie.setOnAction(e -> controller.openDocument("http://www.52pojie.cn/thread-1248586-1-1.html"));

        about.setOnAction(e -> DialogUtils.alert(
                ApplicationConfig.getInstance().getWindow().getTitle() + " , 当前版本: " + ApplicationConfig.VERSION,
                null));

        controller.getIsGetting().addListener((observable, oldValue, newValue) -> {
            openFile.setDisable(newValue);
        });

        controller.getIsDownloading().addListener((observable, oldValue, newValue) -> {
            openFile.setDisable(newValue);
        });

        merger.setOnAction(e -> {
            try {
                Dialog<Void> dialog = DialogUtils.openDialog("/fxml/merger.fxml", controller.getStage());
                dialog.setTitle("合并");
                // dialog.initModality(Modality.NONE);
                dialog.getDialogPane().getChildren().remove(dialog.getDialogPane().lookup(".button-bar"));
                dialog.show();
            } catch (Exception ex) {
                controller.alert(ex.getMessage(), Alert.AlertType.ERROR);
            }
        });
    }

}
